package com.example.base.demo.config;


import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;

/**
 * 配置加密
 *
 * @author TangDan
 * @version 1.0
 * @since 2023/3/6
 */
public class EncryptionEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

    private final String KEY = "qr0cSQPyLDK1TnKD99+RqQ==";

    private final String MYSQL_USERNAME = "mysql.username";

    private final String MYSQL_PASSWORD = "mysql.password";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        // 获取加密的属性
        MutablePropertySources propertySources = environment.getPropertySources();
        PropertySource<?> propertySource = propertySources.get("Config resource 'class path resource [application.yml]' via location 'optional:classpath:/' (document #0)'");
        if (propertySource != null) {
            String userName = (String)propertySource.getProperty(MYSQL_USERNAME);
            String pwd = (String)propertySource.getProperty(MYSQL_PASSWORD);
            // 解密后的配置并添加到环境中
            try {
                String decryptName = decrypt(userName, KEY);
                String decryptPwd = decrypt(pwd, KEY);
                Map<String,Object> map=new HashMap<>();
                map.put(MYSQL_USERNAME,decryptName);
                map.put(MYSQL_PASSWORD,decryptPwd);
                propertySources.addFirst(new SystemEnvironmentPropertySource("decryptResource", map));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 解密
     *
     * @param base64Data 加密后的数据
     * @param base64Key  秘钥
     * @return 原文
     */
    private static String decrypt(String base64Data, String base64Key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(base64Key), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(base64Data));
        return  new String(bytes);
    }


    public static void main(String[] args) throws Exception {
        // AES 生成对称秘钥
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        SecretKey secretKey = generator.generateKey();
        String key = Base64.getEncoder().encodeToString(secretKey.getEncoded());
        System.out.println(key); // qr0cSQPyLDK1TnKD99+RqQ==
        // 加密
        String date = "root";
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] byteEncode = date.getBytes(StandardCharsets.UTF_8);
        byte[] byteAES = cipher.doFinal(byteEncode);
        System.out.println(Base64.getEncoder().encodeToString(byteAES)); // 加密后的内容：xotgJWSxOLJ2qjAZIVVaCw==
        // 解密
        SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] bytes = cipher.doFinal(Base64.getDecoder().decode(Base64.getEncoder().encodeToString(byteAES)));
        System.out.println(new String(bytes)); // 解密后的内容：root
    }
}


